package hsb.ruoyi.generator.controller;


import hsb.ruoyi.common.core.controller.BaseController;
import hsb.ruoyi.common.core.domain.AjaxResult;
import hsb.ruoyi.common.core.page.TableDataInfo;
import hsb.ruoyi.common.core.text.Convert;
import hsb.ruoyi.generator.domain.GenTable;
import hsb.ruoyi.generator.domain.GenTableColumn;
import hsb.ruoyi.generator.service.IGenTableColumnService;
import hsb.ruoyi.generator.service.IGenTableService;
import io.vertx.core.MultiMap;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerResponse;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 *
 * @author ruoyi
 */

@Produces(MediaType.APPLICATION_JSON)
@Path("/tool/gen")
public class GenController extends BaseController {
    @Autowired
    private IGenTableService genTableService;

    @Autowired
    private IGenTableColumnService genTableColumnService;

    /**
     * 查询代码生成列表
     */

    @GET
    @Path("/list")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public TableDataInfo genList(@BeanParam GenTable genTable) {
        startPage();
        List<GenTable> list = genTableService.selectGenTableList(genTable);
        return getDataTable(list);
    }

    /**
     * 修改代码生成业务
     */
    @GET
    @Path(value = "/{tableId}")
    public AjaxResult getInfo(@PathParam(value = "tableId") Long tableId) {
        GenTable table = genTableService.selectGenTableById(tableId);
        List<GenTable> tables = genTableService.selectGenTableAll();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return AjaxResult.success(map);
    }

    /**
     * 查询数据库列表
     */
    @GET
    @Path("/db/list")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public TableDataInfo dataList(@BeanParam GenTable genTable) {
        startPage();
        List<GenTable> list = genTableService.selectDbTableList(genTable);
        return getDataTable(list);
    }

    /**
     * 查询数据表字段列表
     */
    @GET
    @Path(value = "/column/{tableId}")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public TableDataInfo columnList(@PathParam(value = "tableId") Long tableId) {
        TableDataInfo dataInfo = new TableDataInfo();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        dataInfo.setRows(list);
        dataInfo.setTotal(list.size());
        return dataInfo;
    }

    /**
     * 导入表结构（保存）
     */

    @POST
    @Path("/importTable")
    public AjaxResult importTableSave(@QueryParam("tables") String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return AjaxResult.success();
    }

    /**
     * 修改保存代码生成业务
     */
    @PUT
    @Path("/")
    public AjaxResult editSave(@Valid GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return AjaxResult.success();
    }

    /**
     * 删除代码生成
     */
    @DELETE
    @Path("/{tableIds}")
    public AjaxResult remove(@PathParam(value = "tableIds") Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return AjaxResult.success();
    }

    /**
     * 预览代码
     */

    @GET
    @Path("/preview/{tableId}")
    public AjaxResult preview(@PathParam("tableId") Long tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return AjaxResult.success(dataMap);
    }

    /**
     * 生成代码（下载方式）
     */
    @GET
    @Path("/download/{tableName}")
    public void download(@Context HttpServerResponse response, @PathParam("tableName") String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 生成代码（自定义路径）
     */

    @GET
    @Path("/genCode/{tableName}")
    public AjaxResult genCode(@PathParam("tableName") String tableName) {
        genTableService.generatorCode(tableName);
        return AjaxResult.success();
    }

    /**
     * 同步数据库
     */

    @GET
    @Path("/synchDb/{tableName}")
    public AjaxResult synchDb(@PathParam("tableName") String tableName) {
        genTableService.synchDb(tableName);
        return AjaxResult.success();
    }

    /**
     * 批量生成代码
     */

    @GET
    @Path("/batchGenCode")
    public void batchGenCode(@Context HttpServerResponse response,@QueryParam("tables") String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(@Context HttpServerResponse response, byte[] data) throws IOException {
        response.reset();
        MultiMap headers = response.headers();
        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Expose-Headers", "Content-Disposition");
        response.putHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
        headers.add("Content-Length", "" + data.length);
        headers.add("content-type", "application/octet-stream; charset=UTF-8");

        response.end(Buffer.buffer(data));


        //IOUtils.write(data, response.getOutputStream());
    }
}